package com.tarena.csmall.order.web.repository;

import cn.tedu.mall.pojo.order.domain.Order;
import cn.tedu.mall.pojo.order.dto.OrderAddDTO;
import cn.tedu.mall.pojo.order.dto.OrderItemAddDTO;
import cn.tedu.mall.pojo.order.model.OmsOrder;
import cn.tedu.mall.pojo.order.model.OmsOrderItem;
import com.tarena.csmall.order.web.mapper.OrderItemMapper;
import com.tarena.csmall.order.web.mapper.OrderMapper;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class OrderRepositoryImpl implements OrderRepository{
    // 一次性向数据库做批量数据新增 至少 一个订单 一个订单商品
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Override public void orderAdd(OrderAddDTO dto) {
        //先将dto对象属性和order中omsOrder属性 做相同的转化
        OmsOrder omsOrder=new OmsOrder();
        BeanUtils.copyProperties(dto,omsOrder);
        //补充一些没有copy的属性
        omsOrder.setGmtCreate(LocalDateTime.now());
        omsOrder.setGmtModified(omsOrder.getGmtCreate());
        //在映射文件中配置自动生成id 反补会omsOrder
        orderMapper.insertOmsOrder(omsOrder);
        //封装一下orderItems的数据库数据
        List<OmsOrderItem> omsOrderItems=new ArrayList<>();
        //刚刚初始化,数据对象是空元素,遍历dto参数
        for (OrderItemAddDTO item : dto.getOrderItems()) {
            OmsOrderItem omsOrderItem=new OmsOrderItem();
            BeanUtils.copyProperties(item,omsOrderItem);
            //补充一些没有copy的属性
            omsOrderItem.setGmtCreate(omsOrder.getGmtCreate());
            omsOrderItem.setGmtModified(omsOrder.getGmtModified());
            //关联的订单id
            omsOrderItem.setOrderId(omsOrder.getId());
            omsOrderItems.add(omsOrderItem);
        }
        orderItemMapper.insertOmsOrderItems(omsOrderItems);
    }

    @Override public int countOrderSn(String sn) {
        return orderMapper.selectCountBySn(sn);
    }

    @Override public OmsOrder getOrder(String sn) {
        return orderMapper.selectOrderBySn(sn);
    }

    @Override public void clossOrder(String sn) {
        orderMapper.updateStatusBySn(sn,1);
    }
}
